<?php
class User extends AppModel {
	var $name = 'User' ;
	var $actsAs = array ( 'Acl' => 'requester' ) ;
	var $belongsTo = array ( 'Group' => array ( 'className' => 'Group' , 'conditions' => '' , 'order' => '' , 'foreignKey' => 'group_id' ) ) ;
	
	var $validate = array ( 'email' => array ( 'unique' => array ( 'rule' => array ( 'isUnique' , 'email' ) ) , 'format' => array ( 'rule' => array ( 'email' ) ) ) , 'username' => array ( 'unique' => array ( 'rule' => array ( 'isUnique' , 'username' ) ) , 'format' => array ( 'rule' => array ( 'alphaNumeric' ) ) , 'length' => array ( 'rule' => array ( 'between' , 2 , 16 ) ) ) , 'terms' => array ( 'required' => '/1/' ) ) ;
	var $p4ss = null ;
	
	function beforeValidate () {
		$password = $this->generatePassword () ;
		$this->data [ $this->name ] [ "password" ] = Security::hash ( CAKE_SESSION_STRING . $password ) ;
		$this->p4ss = $password ;
		return true ;
	}
	function afterSave () {
		$data = $this->read () ;
		$this->query ( 'UPDATE `aros` SET `alias` = \'' . $data [ 'User' ] [ 'username' ] . '\' WHERE `model` = \'User\' AND `foreign_key` = ' . $data [ 'User' ] [ 'id' ] ) ;
		return true ;
	}
	function generatePassword ( $number = 6 ) {
		$number = ($number < 6) ? 6 : $number ;
		// first character is a-z		$pass = chr ( mt_rand ( 97, 122 ) ) ;
		
		# rest are either 0-9 or a-z or A-Z		for ( $k = 0 ; $k < $number - 1 ; $k ++ ) {
			$probab = mt_rand ( 1, 10 ) ;
			if ($probab <= 5) // a-z probability is 50%
				$pass .= chr ( mt_rand ( 97, 122 ) ) ; elseif ($probab <= 8 && $probab > 5) // 0-9 probability is 30%
				$pass .= chr ( mt_rand ( 48, 57 ) ) ; else
				$pass .= chr ( mt_rand ( 65, 89 ) ) ; // 0-9 probability is 20%
		}
		
		return $pass ;
	}
	function validateLogin ( $data ) {
		
		$user = $this->find ( array ( 'username' => $data [ 'username' ] , 
		//    'password' => Security::hash(CAKE_SESSION_STRING . $data['password'])), 		'password' => md5 ( $data [ 'password' ] ) ), array ( 'id' , 'username' ) ) ;
		
		
		if (empty ( $user ) == false)
			return $user [ 'User' ] ;
		return false ;
	}
	function parentNode () {
		if (! $this->id) {
			return null ;
		}
		
		$data = $this->read () ;
		
		if (! $data [ 'User' ] [ 'group_id' ]) {
			return null ;
		} else {
			return array ( 'model' => 'Group' , 'foreign_key' => $data [ 'User' ] [ 'group_id' ] ) ;
		}
	}

}
?>